﻿using Org.BouncyCastle.Utilities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace InfrastructureBase.Data.Utils
{
    /// <summary>
    /// 文件相关帮助类
    /// </summary>
    public class FileConvertHelper
    {
        /// <summary>
        /// 将 Stream 转成 byte[] 
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>

        public byte[] StreamToBytes(Stream stream)
        {

            byte[] bytes = new byte[stream.Length];
            stream.Read(bytes, 0, bytes.Length);
            // 设置当前流的位置为流的开始 
            stream.Seek(0, SeekOrigin.Begin);
            return bytes;
        }

        /// <summary>
        /// 将 byte[] 转成 Stream 
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public Stream BytesToStream(byte[] bytes)
        {
            using MemoryStream stream = new MemoryStream(bytes);
            return stream;
        }

        /// <summary>
        /// 将 Stream 写入文件 
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="fileName"></param>
        public void StreamToFile(Stream stream, string fileName)
        {

            // 把 Stream 转换成 byte[] 
            byte[] bytes = new byte[stream.Length];
            stream.Read(bytes, 0, bytes.Length);
            // 设置当前流的位置为流的开始 
            stream.Seek(0, SeekOrigin.Begin);
            // 把 byte[] 写入文件 
            using (FileStream fs = new FileStream(fileName, FileMode.Create))
            {
                using BinaryWriter bw = new BinaryWriter(fs);
                bw.Write(bytes);
            };
        }

        /// <summary>
        /// 从文件读取 Stream 
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public Stream FileToStream(string fileName)
        {
            Stream stream = null;
            using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                byte[] bytes = new byte[fileStream.Length];
                fileStream.Read(bytes, 0, bytes.Length);
                using (stream = new MemoryStream(bytes)) { };
            }
            return stream;
        }
    }
}
